package com.tricycle.scada.mqtt.realtime;

import com.tricycle.scada.mqtt.entity.RealtimeValueEntity;
import com.tricycle.scada.mqtt.model.RealtimeMessageModel;
import com.tricycle.scada.mqtt.model.RealtimeValueModel;
import com.tricycle.scada.mqtt.service.RealtimeValueService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.CRC32;

//@Component
public class RealtimeMySQLHandler implements RealtimeValueHandler {

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    private RealtimeValueService realtimeValueService;

    public RealtimeMySQLHandler(RealtimeValueService realtimeValueService) {
        this.realtimeValueService = realtimeValueService;
    }

    public void handle(RealtimeMessageModel message) {

        executorService.submit(() -> {
            List<RealtimeValueEntity> realtimeList = new ArrayList<>();
            for (RealtimeValueModel value : message.getRealtimeValues()) {
                CRC32 crc32 = new CRC32();
                crc32.update(value.getName().getBytes());
                RealtimeValueEntity realtime = new RealtimeValueEntity();
                realtime.setName(crc32.getValue());
                realtime.setTime(value.getTimestamp());
                realtime.setValue(value.getValue().toString());
                realtime.setValueType(value.getType());
                realtimeList.add(realtime);
            }
            realtimeValueService.saveBatch(realtimeList);
        });

    }
}

